<template>
  <div style="width:98%;margin-left:1%;margin-top:2%;display:block;">
    <a-table bordered :dataSource="dataSource" :columns="columns"  :scroll="{ x:2580,y:525 }">

      <template slot="username" slot-scope="text, record">
        <editable-cell
                :ref="`username_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.username"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'username', $event)"/>
      </template>
      <template slot="email" slot-scope="text, record">
        <editable-cell
                :ref="`email_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.email"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'email', $event)"/>
      </template>
      <template slot="firstName" slot-scope="text, record">
        <editable-cell
                :ref="`firstName_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.firstName"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'firstName', $event)"/>
      </template>
      <template slot="lastName" slot-scope="text, record">
        <editable-cell
                :ref="`lastName_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.lastName"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'lastName', $event)"/>
      </template>
      <template slot="status" slot-scope="text, record">
        <editable-cell
                :ref="`status_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.status"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'status', $event)"/>
      </template>
      <template slot="address1" slot-scope="text, record">
        <editable-cell
                :ref="`address1_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.address1"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'address1', $event)"/>
      </template>
      <template slot="address2" slot-scope="text, record">
        <editable-cell
                :ref="`address2_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.address2"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'address2', $event)"/>
      </template>
      <template slot="city" slot-scope="text, record">
        <editable-cell
                :ref="`city_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.city"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'city', $event)"/>
      </template>
      <template slot="state" slot-scope="text, record">
        <editable-cell
                :ref="`state_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.state"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'state', $event)"/>
      </template>
      <template slot="zip" slot-scope="text, record">
        <editable-cell
                :ref="`zip_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.zip"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'zip', $event)"/>
      </template>
      <template slot="country" slot-scope="text, record">
        <editable-cell
                :ref="`country_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.country"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'country', $event)"/>
      </template>
      <template slot="phone" slot-scope="text, record">
        <editable-cell
                :ref="`phone_${record.key}`"
                :defaultEditable="record.editable"
                :autoSave=true
                :required="true"
                :decoratorOptions="rules.phone"
                placeholder='请输入'
                :value="text"
                :text="text"
                @valueChange="onCellChange(record.key, 'phone', $event)"/>
      </template>
      <template slot="operation" slot-scope="text, record">
        <div class='editable-row-operations'>
          <span v-if="record.editable">
            <a @click="() => save(record.key)">保存</a>
              <a-divider type="vertical" />
            <a-popconfirm title='确定取消吗?' @confirm="() => cancel(record.key)">
              <a>取消</a>
              <a-divider type="vertical" />
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="() => edit(record.key)">编辑</a>
              <a-divider type="vertical" />
            <a @click="() => reset(record.key)" :visibility="visible">重置</a>
              <a-divider type="vertical" />
          </span>
          <a-popconfirm v-if="dataSource.length" title="确定删除吗?" @confirm="() => onDelete(record.key)">
            <span>
              <a href="javascript:;">删除</a>
            </span>
          </a-popconfirm>
        </div>
      </template>

    </a-table>

    <a-button class="editable-add-btn" @click="handleAdd" type="primary" style="float:right;" :disabled="disable">新增用户</a-button>
    <!-- <a-button type="primary" @click="handleSave" style="float:right;right:2%">提交修改</a-button> -->
  </div>
</template>
<script>
  import EditableCell from '@/components/cell.vue';
  import moment from 'moment';
  import { mapActions , mapState} from 'vuex'
  /*
  * EditableCell Code https://github.com/vueComponent/ant-design-vue/blob/master/components/table/demo/EditableCell.vue
  */
  export default {
    components: {
      EditableCell,
    },
    computed: {
      ...mapState({
        signIn: state => state.account.signIn,
        account: state => state.account.account
      })
    },
    data() {
      return {
        visible : true,
        disable :false,
        signData: [],
        mulData: [],
        dateFormat: 'YYYY-MM-DD',
        dataSource: [
        ],
        count: 1,
        columns: [
          {
            title: '用户账号',
            dataIndex: 'user_id',
            width: '150',
            scopedSlots: { customRender: 'user_id' },
          },
          {
            title: '用户昵称',
            dataIndex: 'nick_name',
            width: '150',
            scopedSlots: { customRender: 'nick_name' },
          },
          {
            title: '学校信息',
            dataIndex: 'school',
            width: '150',
            scopedSlots: { customRender: 'school' },
          },
          {
            title: '寝室信息',
            dataIndex: 'dormitory',
            width: '150',
            scopedSlots: { customRender: 'dormitory' },
          },
          {
            title: '校园卡号',
            dataIndex: 'stu_id',
            width: '150',
            scopedSlots: { customRender: 'stu_id' },
          },
          {
            title: '身份证号',
            dataIndex: 'id_card',
            width: '150',
            scopedSlots: { customRender: 'id_card' },
          },
          {
            title: '联系方式',
            dataIndex: 'phone',
            width: '150',
            scopedSlots: { customRender: 'phone' },
          },

          {
            title: '密码',
            dataIndex: 'password',
            width: '150',
            scopedSlots: { customRender: 'password'},
          },
          {
            title: '操作',
            dataIndex: 'operation',
            width: '100',
            scopedSlots: { customRender: 'operation' },
            fixed: 'right',
          },
        ],
        fields:['user_id','nick_name','school','dormitory','stu_id','id_card','phone','password'],
      };
    },
    methods: {
      ...mapActions({
      getAccountList: 'account/getAccountList',
      updateAccount: 'account/updateAccount',
    }),
      moment,
      // 模糊搜索
      handleSearch(value) {
        let result;
        if (!value || value.indexOf('@') >= 0) {
          result = [];
        } else {
          result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
        }
        this.emailList = result
      },
      // input Change事件
      onCellChange(key, dataIndex, value) {
        // console.log(`${dataIndex}：${value} `);
        const dataSource = [...this.dataSource];
        const target = dataSource.find(item => item.key === key);
        if (target) {
            target[dataIndex] = value;
          this.dataSource = dataSource;
        }
      },
      // 删除
      onDelete(key) {
        // 拷贝数组数据
        const dataSource = [...this.dataSource];
        // 过滤移除当前项目
        this.dataSource = dataSource.filter(item => item.key !== key);
        if(key==this.count-1) this.disable = false
        let deleteD = dataSource[key]
        this.deleteAccount({username:deleteD.username}).then((res)=>{
          this.openNotification("OK","删除用户信息成功",res)
        },(error)=>{
          this.openNotification("NOK","删除用户信息失败",error)
        })
      },
      // 点击编辑
      edit(key) {
        const newData = [...this.dataSource];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          target.editable = true;
          this.dataSource = newData;
        }
        this.visible = false;
      },
      // 点击保存
      save(key) {
        this.validateRow(key, this.fields, (err, values) => {
          if (!err) {
            const newData = [...this.dataSource];
            const row = newData.find(item => key === item.key);
            if (row) {
              // 用户数据合并到原对象上
              Object.assign(row, values);
              delete row.editable;
              this.signData = row;
              // console.log('单行保存row', row);
              // target 保存了最新行数据，可以提价到后台
              this.dataSource = newData;

              this.visible = true;
              if(key==this.count)
              {
                this.disable = false
                this.addAccount(newData[key]).then((res)=>{
                  this.count = newData.length
                  this.openNotification("OK","新增用户信息成功",res)
                },(error)=>{
                  this.openNotification("NOK","新增用户信息失败",error)
                })

              }
              else
              {
                let a = newData[key]
                this.updateAccount({
                  type:'updateAccount',
                  username:a.username,
                  email:a.email,
                  firstName:a.firstName,
                  lastName:a.lastName,
                  status:a.status,
                  address1:a.address1,
                  address2:a.address2,
                  city:a.city,
                  state:a.state,
                  zip:a.zip,
                  country:a.country,
                  phone:a.phone}).then((res)=>{
                    this.openNotification("OK","更新用户信息成功",res)
                  },(error)=>{
                    this.openNotification("NOK","更新用户信息失败",error)
                  })

              }
            }
          }
        });

      },
      // 点击取消
      cancel(key) {
        const newData = [...this.dataSource];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          delete target.editable;
          this.dataSource = newData;
        }
        this.visible = true
        if(key==this.count-1) this.disable = false
      },
      reset(key){
        let resetD = this.dataSource[key]
        this.resetAccount({type:"updateSignon",username:resetD.username,password:"123456"}).then((res)=>{
          this.openNotification("OK","重置用户密码成功",res)
        },(error)=>{
          this.openNotification("NOK","重置用户密码失败",error)
        })
      },
      // validateRow可以提取为公共函数
      validateRow(key, fields, callback) {
        // 查找验证是否通过
        const row = {};
        let err = false;
        // forEach 对每一个验证，可以更改为some满足一个就提醒
        fields.forEach(filed => {
          let refName = `${filed}_${key}`;
          let result = this.$refs[refName].validate();
          row[filed] = result.value;
          if (!result.success) {
            err = true;
          }
        });
        callback(err, row);
      },
      // 批量提交保存数据
      handleSave() {
        const newData = [...this.dataSource];
        // 找出处于可编辑行
        const rows = newData.filter(row => {
          return row.editable;
        });
        let count = dataSource.length;
        // 一个个校验行
        rows.forEach(row => {
          this.validateRow(row.key, this.fields, (err, values) => {
            if (!err) {
              // 行记录数据合并到row中
              Object.assign(row, values);
              count++;
            }
          });
        });
        // 最终数据在rows中;
        if (rows.length === count) {
          // 数据在rows,提交数据
          this.mulData = rows;
          // console.log('批量多行rows', rows);
        }
      },
      openNotification(type,title,msg) {
      let iconType = ''
      let iconColor = ''
      if(type=='OK'){
        iconType = 'smile'
        iconColor = '#52c41a'
      }
      else
      {
        iconType = 'frown'
        iconColor = '#eb2f96'
      }
      this.$notification.open({
        message: title,
        description: msg,
        icon: h => h('a-icon', {
          props: {
            type: iconType,
            theme: 'twoTone',
            'two-tone-color': iconColor
          }
        }),

      });
    }
    },
    mounted(){
      if(this.signIn===false||this.account===null){
        this.openNotification("NOK","未登录","请先登录管理员账号!")
        this.$router.push("/mainPage/login")
      }
      else{
        this.getAccountList().then((res) => {
          let i = 0
          for(let item of res){
            item.key = i++
            this.dataSource.push(item);
          }
          this.count = this.dataSource.length
          this.openNotification("OK","更新用户列表成功","用户列表已更新!")
          console.log(this.dataSource)
        }, (error) => {
          this.openNotification("NOK","更新用户列表失败",error)
        })
      }
    }
  };
</script>
<style scoped>
  .editable-row-operations a {
    margin-right: 8px;
  }
  li {
    text-align: left;
  }
  pre {
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.65);
    color: #ccc;
  }
</style>
